from PyQt4 import QtGui
from PyQt4.QtCore import Qt
import S3DPath
from S3D import QtHelper
from S3D.Tools.Sound.EventSearcher.UI.ListSelectDialog import Ui_ListSelectDialog
from PyQt4.QtGui import QListWidgetItem

class ListSelectDialog(QtGui.QDialog):
    def __init__(self, parent, elements, lastSelected):
        super(ListSelectDialog, self).__init__(parent)

        self.ui = Ui_ListSelectDialog()
        self.ui.setupUi(self)

        self.elements = elements or []
        self.lastSelected = lastSelected

        self.initUi()

    def initUi(self):
        for name in self.elements:
            item = QListWidgetItem(name)
            item.name = name
            self.ui.elementsList.addItem(item)

            if name in self.lastSelected:
                item.setCheckState(Qt.Checked)
            else:
                item.setCheckState(Qt.Unchecked)

    def onSelectAll(self):
        for item in QtHelper.items(self.ui.elementsList):
            item.setCheckState(Qt.Checked)

    def onSelectNone(self):
        for item in QtHelper.items(self.ui.elementsList):
            item.setCheckState(Qt.Unchecked)

    def onAccept(self):
        self.selectedElements = []
        for item in QtHelper.items(self.ui.elementsList):
            if item.checkState() == Qt.Checked:
                self.selectedElements.append(item.name)
        self.accept()

if __name__ == "__main__":
    dlg = ListSelectDialog(None, ["a", "b", "c", "d"], ["a", "d"])
    if dlg.exec_() == QtGui.QDialog.Accepted:
        print("Selected: %r" % dlg.selectedElements)